package com.ashlikun.scan.simple

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.ashlikun.camera.scan.AnalyzeResult
import com.ashlikun.camera.scan.util.CameraXLogUtils
import com.ashlikun.scan.simple.databinding.ActivityStyle2Binding
import com.ashlikun.zxing.DecodeConfig
import com.ashlikun.zxing.analyze.QRCodeAnalyzer
import com.google.zxing.Result

/**
 * 二维码扫码 示例
 */
class QRCodeStyle2ScanActivity : AppCompatActivity() {
    companion object {
        fun startSelf(context: Context) {
            context.startActivity(Intent(context, QRCodeStyle2ScanActivity::class.java))
        }
    }

    val binding by lazy {
        ActivityStyle2Binding.inflate(layoutInflater)
    }

    private var toast: Toast? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.scanBarView.also { view ->
            view.setInitCameraScanCall {
                // 根据需要设置CameraScan相关配置
                it.setPlayBeep(true)
                it.setVibrate(true)
            }
            view.resultAnalyzer.also {
                // 初始化解码配置
                val decodeConfig = DecodeConfig(
                    areaRectRatio = 1.0f,
                    // 设置是否支持扫垂直的条码
                    isSupportVerticalCode = false,
                    // 设置是否支持识别反色码，黑白颜色反转
                    isSupportLuminanceInvert = true,
                    isSupportLuminanceInvertMultiDecode = true,
                    //是否支持多个码一起识别
                    isMultipleCode = true
                )
                // 多格式分析器（支持的条码格式主要包含：一维码和二维码）
                it.setAnalyzer(QRCodeAnalyzer(decodeConfig))
            }
            view.setScanResultCallback {
                // 停止分析
                view.cameraScan.setAnalyzeImage(false)

                // 处理扫码结果相关逻辑（此处弹Toast只是为了演示）
                showToast(it.result.text)
                // 继续分析
                view.cameraScan.setAnalyzeImage(true)
            }
            view.synchLifeStart(lifecycle)
        }
    }

    private fun print(results: AnalyzeResult<Result>) {
        results.resultAll.forEachIndexed { index, result ->
            CameraXLogUtils.e("第${index + 1}个码 text = ${result.text},,,resultPoints = ${result.resultPoints}")
        }
    }

    private fun showToast(text: String) {
        toast?.cancel()
        toast = Toast.makeText(this, text, Toast.LENGTH_SHORT)
        toast?.show()
    }
}